/**
* 设备管理 设备借出与归还
*/
<template>
  <div style="width: 100%;height: 100%">
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.userName" placeholder="请输入患者姓名或手机号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="searchByNameOrPhone">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
      </el-col>

      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="deviceBorrow">
          <font-awesome-icon icon="fas fa-plus" />
          <span style="margin-left:1vh">设备借出</span>
        </el-button>
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="handleAdd">
          <font-awesome-icon icon="fas fa-plus" />
          <span style="margin-left:1vh">患者录入</span>
        </el-button>
      </el-col>
      <el-col :span="16">
      </el-col>
    </el-row>


    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>



    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[5, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="100"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>



    <!--列表-->
    <el-table
        :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }"
        size="large"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;height: 50%"
        :data="userList"
        v-loading="loading"
        highlight-current-row
        class="customer-table"
        border
        element-loading-text="拼命加载中">
      <el-table-column sortable prop="deviceSerialCode" label="设备序列号" width="200" >
        <template #default="scope">
          <div>{{removeSubstring(scope.row.serialCode,"ynu",false,true)}}</div>
        </template>
      </el-table-column>
      <el-table-column  sortable prop="name" label="患者姓名" width="150">
      </el-table-column>
      <el-table-column  sortable prop="phoneNum" label="手机号" width="150">
      </el-table-column>
      <el-table-column  prop="status" label="设备状态" width="100">
      </el-table-column>
      <el-table-column sortable prop="borrowTime" label="设备借出时间" width="300">
      </el-table-column>
      <el-table-column sortable prop="returnTime" label="设备归还时间" width="300">
      </el-table-column>

      <el-table-column fixed="right" label="操作" min-width="300">
        <template v-slot="scope">
          <!-- 如果 returnTime 有数据，显示“已归还”按钮 -->
          <el-button
              v-if="scope.row.returnTime"
              size="default"
              type="success"
              @click="handleReturned(scope.row)"
          >
            <font-awesome-icon icon="fas fa-check" />
            <span style="margin-left:1vh">已归还</span>
          </el-button>
          <!-- 如果 returnTime 没有数据，显示“归还”按钮 -->
          <el-button
              v-else
              size="default"
              type="danger"
              @click="handleEdit(scope.row)"
          >
            <font-awesome-icon icon="fas fa-edit" />
            <span style="margin-left:1vh">归还</span>
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--  设备借出  -->
    <el-dialog title="设备借出" v-model="borrowFormVisible" width="30%" align-center center @close="borrowFormClose">
      <el-form style="display: flex;align-items: center;justify-content: center;width: 100%;height: 100%;flex-wrap: wrap">

        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">姓名:</el-text>
          <el-select
              v-model="borrowForm.userId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入患者姓名"
              :remote-method="queryUsers"
              :loading="loading"
              style="width: 80%;"
              clearable
          >
            <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.name "
                :value="item.userId"
            >
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">设备序列号:</el-text>
          <el-select
              v-model="borrowForm.deviceSerialCode"
              filterable
              remote
              reserve-keyword
              placeholder="请输入设备序列号"
              :remote-method="querySerialCode"
              :loading="loading"
              style="width: 80%;"
              clearable
          >
            <el-option
                v-for="item in serialCodeOptions"
                :key="item"
                :label="item"
                :value="item"
            >
              <span>{{ item }}</span>
            </el-option>
          </el-select>

        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelBorrow">取消</el-button>
        <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="confirmBorrow">保存</el-button>
      </span>
      </template>
    </el-dialog>

    <!--  患者录入  -->
    <el-dialog title="患者录入" v-model="addFormVisible" width="30%" align-center center @close="addFormClose">
      <el-form style="display: flex;align-items: center;justify-content: center;width: 100%;height: 100%;flex-wrap: wrap">
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">姓名:</el-text>
          <el-input style="width: 80%" v-model="addForm.name" placeholder="请输入患者姓名" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">手机号:</el-text>
          <el-input style="width: 80%" v-model="addForm.username" placeholder="请输入患者手机号" autocomplete="off" />
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">身高（cm）:</el-text>
          <el-input style="width: 80%" v-model="addForm.height" placeholder="请输入患者身高" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">体重（kg）:</el-text>
          <el-input style="width: 80%" v-model="addForm.weight" placeholder="请输入患者体重" autocomplete="off"/>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">性别:</el-text>
          <el-select style="width: 80%" v-model="addForm.sex" placeholder="请选择患者性别" autocomplete="off">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item style="width: 100%;display: flex;align-items: center;justify-content: center;flex-direction: row">
          <el-text size="large" style="width: 20%">出生日期:</el-text>
          <div class="block">
            <el-date-picker
                autocomplete="off"
                v-model="addForm.birthTime"
                type="date"
                :disabled-date="disabledDate"
                placeholder="请输入患者出生日期"
                value-format="YYYY-MM-DD"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAdd">取消</el-button>
        <el-button type="primary" style="background-color: #04c1a5;border: 0" @click="confirmAdd">保存</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import Pagination from '../../components/Pagination.vue';
import {onMounted, ref} from "vue";
import doctor from "@/api/doctor.js";
import user from "@/api/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import * as dateUtils from "@/utils/dateUtils.js";
import FilterList from "@/components/tableViews/filterList.vue";
import {formatDateTime} from "@/utils/dateUtils.js";
import admin from "@/api/admin.js";
import {removeSubstring} from "@/utils/strFormat.js";
const loading = ref(false);
const title = ref('添加用户');

const userList = ref([]);
const userOptions = ref([]);
const serialCodeOptions =  ref([]);
const disabledDate = (time) => {
  return time.getTime() > Date.now()
};
//按钮查询过滤
const rows = ref([
  { label: '设备状态', buttons: [
      { text: '-全部-', value: null, selected: true },
      { text: '未归还', value: 0, selected: false },
      { text: '已归还', value: 1, selected: false },
    ] },
  { label: '设备借出时长', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: -1,selected: false },
    ] },
  { label: '设备归还时长', buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: -1,selected: false },
    ] },
]);



const updateList = (rows) =>{
  const userSearchQuery = {
    name:formInline.value.userName,
    phoneNum:formInline.value.userName,
    status:null,
    borrowMinTime:'',
    returnMinTime:'',
    borrowMaxTime:'',
    returnMaxTime:'',
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }

  // 调用更新方法
  updateUserSearchQuery(rows, userSearchQuery);
  requestUserList(userSearchQuery);
}

//分页模块
const pageParam = ref({
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const userSearchQuery = {
    name:formInline.value.userName,
    phoneNum:formInline.value.userName,
    status:null,
    borrowMinTime:'',
    returnMinTime:'',
    borrowMaxTime:'',
    returnMaxTime:'',
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  // 调用更新方法
  updateUserSearchQuery(rows.value, userSearchQuery);
  //执行查询
  requestUserList(userSearchQuery);
}

const handleSizeChange = ()=>{
  const deviceListQuery = {

    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }

  updateUserSearchQuery(rows.value,deviceListQuery)
  requestUserList(deviceListQuery)
}



function updatePageParams(pageData) {
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}
function updateSelectedValue(buttons) {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}

function updateTime(buttons, currentDate) {
  for (const button of buttons) {
    if (button.selected) {
      if (button.value === -1) {
        // 对于“一年以上”按钮，设置 borrowMaxTime 为一年前的日期
        const time = new Date();
        time.setFullYear(time.getFullYear() - 1);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else if (button.value === null) {
        // 对于“全部”按钮，返回 null，表示不限制时间
        return null;
      } else {
        // 其他按钮，根据 value 计算时间范围
        const time = new Date();
        time.setDate(time.getDate() - button.value);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
  return currentDate; // 默认取当前时间
}


//列表查询
onMounted(() => {
  getUserList();
});
const updateUserSearchQuery = (rows, userSearchQuery)=>{
  userSearchQuery.status = updateSelectedValue(rows[0].buttons);

  // userSearchQuery.currentTime = dateUtils.getCurrentDate();
  userSearchQuery.borrowMinTime = updateTime(rows[1].buttons,userSearchQuery.borrowMaxTime);
  userSearchQuery.returnMinTime = updateTime(rows[2].buttons,userSearchQuery.returnMaxTime);

  // 如果“一年以上”按钮被选中，设置 borrowMaxTime 或 returnMaxTime 为一年前的日期
  if (rows[1].buttons.find(button => button.selected && button.value === -1)) {
    userSearchQuery.borrowMaxTime = updateTime(rows[1].buttons, userSearchQuery.borrowMaxTime);
    userSearchQuery.borrowMinTime = null; // 设置 borrowMinTime 为 null
  }
  if (rows[2].buttons.find(button => button.selected && button.value === -1)) {
    userSearchQuery.returnMaxTime = updateTime(rows[2].buttons, userSearchQuery.returnMaxTime);
    userSearchQuery.returnMinTime = null; // 设置 returnMinTime 为 null
  }
  console.log('Query Parameters:', userSearchQuery);
}
const requestUserList = (userSearchQuery)=>{
  loading.value = true;
  userSearchQuery.currentPage=userSearchQuery.pageIndex+1

  doctor.getDeviceUsesList(userSearchQuery)
      .then((res) => {
        console.log('res111',res)
        if (res.data.code === 200) {
          // 将状态码转换为中文描述
          // 将状态码转换为中文描述

          userList.value = res.data.data.result.map(device => ({
            ...device,
            status: getStatusText(device.status),
            borrowTime:formatDateTime(device.borrowTime),
            returnTime:formatDateTime(device.returnTime)
          }));
        }
        updatePageParams(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(()=>{
        loading.value = false;
      })
  ;
}
const getUserList = ()=>{
  const userSearchQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  requestUserList(userSearchQuery)
}





const getStatusText = (statusCode) => {
  switch (statusCode) {
    case 0:
      return "未归还";
    case 1:
      return "已归还";
    default:
      return "";
  }
};







//编辑弹窗
const formInline = ref({
  userName: '',
  userMobile: '',
  serialCode:''
});
const handleEdit = (deviceUse)=>{
  ElMessageBox.confirm(
      '确定归还设备吗',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        confirmEdit(deviceUse)
      })
}
const handleReturned = (deviceUse) => {
  ElMessage.success('设备已归还');
};

//根据时间戳计算年龄
function calculateAge(birthTimestamp) {
  // 创建表示当前日期和出生日期的 Date 对象
  const now = new Date();
  const birthDate = new Date(birthTimestamp);

  // 计算年份差异
  let age = now.getFullYear() - birthDate.getFullYear();

  // 获取当前月份和日期
  const month = now.getMonth() - birthDate.getMonth();
  const day = now.getDate() - birthDate.getDate();

  // 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减 1
  if (month < 0 || (month === 0 && day < 0)) {
    age--;
  }

  return age;
}

const confirmEdit = (deviceUse)=>{
  const data={
    "userId": deviceUse.userId,
    "deviceSerialCode": deviceUse.deviceSerialCode
  }

  doctor.returnDevice(data)
      .then((res)=>{
    if (res.data.code === 200){
      ElMessage.success(res.data.msg)
      getUserList();
    }else{
      ElMessage.error(res.data.msg)
    }

  }).catch((err)=>{
    console.log(err)
  })

}



//信息查询
const searchByNameOrPhone = ()=>{
  let userSearchQuery = {
    status: updateSelectedValue(rows.value[0].buttons),
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  if (formInline.value.userName.length === 11){
    userSearchQuery.searchKey = formInline.value.userName
  }else{
    userSearchQuery.searchKey = formInline.value.userName
  }
  requestUserList(userSearchQuery)
}


//设备借出 新增弹窗
const borrowFormVisible = ref(false);
const borrowForm = ref({
  userId:'',
  deviceSerialCode:'',
})
const deviceBorrow = () => {
  borrowFormVisible.value=true;
}
const borrowFormClose = () =>{
  borrowForm.value.userId = '';
  borrowForm.value.deviceSerialCode = '';
}
const confirmBorrow = () =>{
  doctor.borrowDeviceToHom(borrowForm.value)
  .then((res)=>{
    if (res.data.code){
      ElMessage.success(res.data.msg);
      getUserList();
    }else{
      ElMessage.error(res.data.msg);
    }
    getUserList();
  }).catch((err)=>{
    console.log(err);
  }).finally(()=>{
    borrowFormVisible.value = false;
  })
}
const cancelBorrow = () => {
  borrowFormVisible.value = false;
}

// 模糊查询用户
const queryUsers = (query) => {
  if (query !== '') {
    loading.value = true;
    user
        .searchUserByName({ name: query })
        .then((res) => {
          if (res.data.code === 200) {
            userOptions.value = res.data.data;
            loading.value = false;
          } else {
            ElMessage.error(res.data.msg);
            loading.value = false;
          }
        })
        .catch((err) => {
          console.error(err);
          loading.value = false;
        });
  } else {
    userOptions.value = [];
  }
};
//模糊查询设备序列号
const querySerialCode = (query) => {
  console.log("querySerialCode",query)
  if (query !== '') {
    loading.value = true;
    doctor
        .getLikeDeviceSerialCode({ serialCode: query })
        .then((res) => {
          if (res.data.code === 200) {
            serialCodeOptions.value = res.data.data;
            loading.value = false;
          } else {
            ElMessage.error(res.data.msg);
            loading.value = false;
          }
        })
        .catch((err) => {
          console.error(err);
          loading.value = false;
        });
  } else {
    serialCodeOptions.value = [];
  }
};




//患者录入 新增弹窗
const addFormVisible = ref(false);
const addForm = ref({
  name:'',
  username: '',
  height:0,
  weight:0,
  sex:'',
  birthTime:0,
});
const handleAdd = ()=>{
  addFormVisible.value = true;
}
const addFormClose = ()=>{
  addForm.value.name = '';
  addForm.value.username = '';
  addForm.value.height = 0;
  addForm.value.weight = 0;
  addForm.value.sex = '';
  addForm.value.birthTime = 0;
}
const confirmAdd = ()=>{
// 手机号校验
  const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号正则表达式
  if (!phoneRegex.test(addForm.value.username)) {
    ElMessage.error('请输入有效的手机号');
    return;
  }
  // 将出生日期字符串转换为时间戳
  if (addForm.value.birthTime) {
    const date = new Date(addForm.value.birthTime); // 将日期字符串转换为 Date 对象
    addForm.value.birthTime = date.getTime(); // 获取时间戳
  }
  admin.addUser(addForm.value).then((res)=>{
    console.log('birthTime',res)
    if (res.data.code === 200){
      ElMessage.success(res.data.msg);
    }else{
      ElMessage.error(res.data.msg);
    }
    getUserList();
  }).catch((err)=>{
    console.log(err);
  }).finally(()=>{
    addFormVisible.value = false;
  })
}
const cancelAdd = ()=>{
  addFormVisible.value = false;
}





</script>
<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
::v-deep .customer-table th{
  border:none;
}
::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  /* background-color:#04c1a5; */
  background-color: green;
  color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled) {
  background-color: #04c1a5;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}
</style>